package motionsApp.client.labeling;

import java.util.Collection;
import java.util.Set;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.SuggestBox;

public class MotionToLabelPainter {

	final private Grid table;
	private MultiWordSuggestOracle labelsSource;
	private SuggestBox newLabelTextBox;	

	public MotionToLabelPainter(HasWidgets panel, final LabelAddedCallback addedCallback) {		
		table = new Grid(2,4);
		panel.add(table);
		labelsSource = new MultiWordSuggestOracle();		
		newLabelTextBox = new SuggestBox(labelsSource);		
		table.setWidget(0, 2, newLabelTextBox);
		Button addLabelButton = new Button("Add");
		addLabelButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				String newLabel = newLabelTextBox.getText();
				addedCallback.labelAdded(newLabel);
				newLabelTextBox.setText(null);
				
			}
		});
		table.setWidget(0, 3, addLabelButton);
		Button nextMotionButton = new Button("Next motion");
		nextMotionButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				addedCallback.newMotionRequested();
				
			}
		});
		
		table.setWidget(1, 3, nextMotionButton);
		
		setMotion("Waiting for motion", null);
	}
	
	public void setAvailableLabels(Set<String> labels){
		labelsSource.clear();
		labelsSource.addAll(labels);
	}

	public void setMotion(String motion, Collection<String> labels) {
		String labelsToShow = joinLabels(labels);
		table.setText(0, 0, motion);
		table.setText(0, 1, labelsToShow);
	}

	private String joinLabels(Collection<String> labels) {
		if(labels == null || labels.size() == 0){
			return "";
		}
		
		Object[] array = labels.toArray();
		String joined = '(' + array[0].toString();
		for(int i = 1; i < labels.size(); i++){
			joined += ';' + array[i].toString();
		}
		
		joined+= ')';
			
		return joined;
	}
}
